<!-- 在线人数显示组件 -->
<template>
  <div class="online-count">
    <el-badge :value="onlineCount" class="online-badge">
      <i class="el-icon-user"></i>
      <span>在线人数</span>
    </el-badge>
  </div>
</template>

<script>
export default {
  name: 'OnlineCount',
  data() {
    return {
      onlineCount: 0,
      ws: null
    }
  },
  created() {
    this.connectWebSocket()
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close()
    }
  },
  methods: {
    connectWebSocket() {
      // 创建WebSocket连接
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
      const wsUrl = `${protocol}//${window.location.host}/api/ws/online`
      
      this.ws = new WebSocket(wsUrl)
      
      // 连接成功回调
      this.ws.onopen = () => {
        console.log('WebSocket连接成功')
      }
      
      // 收到消息回调
      this.ws.onmessage = (event) => {
        this.onlineCount = parseInt(event.data)
      }
      
      // 连接关闭回调
      this.ws.onclose = () => {
        console.log('WebSocket连接关闭')
        // 尝试重新连接
        setTimeout(() => {
          this.connectWebSocket()
        }, 5000)
      }
      
      // 连接错误回调
      this.ws.onerror = (error) => {
        console.error('WebSocket连接错误:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.online-count {
  display: inline-block;
  margin-right: 20px;
  
  .online-badge {
    .el-icon-user {
      font-size: 16px;
      margin-right: 5px;
    }
  }
}
</style> 